package com.eightywork.life.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.eightywork.life.R;
import com.eightywork.life.activity.IndexActivity;
import com.eightywork.life.adapter.NeighborListAdapter;
import com.eightywork.life.model.Space;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.ActionsContentView;
import com.eightywork.life.widget.RTPullListView;
import com.eightywork.life.widget.RTPullListView.OnRefreshListener;
import com.eightywork.life.widget.RTPullListView.OnScrollStopAndEndListener;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class NeighbourFragment extends BaseFragment implements OnClickListener {
	public static final String TAG = NeighbourFragment.class.getName();
	private ActionsContentView viewActionsContentView;
	private ImageButton rightButton;
	private RTPullListView listView;
	private NeighborListAdapter adapter;
	private List<Space> list = new ArrayList<Space>();
	private TextView headerTitle;
	private AsyncTask<?, ?, ?> task;
	private String group = "0";
	private int page = 1;
	private boolean isLoading, isRefresh;
	//private ViewGroup footView;
	private List<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>();

	public NeighbourFragment(Activity context,
			ActionsContentView viewActionsContentView) {
		this.viewActionsContentView = viewActionsContentView;
	}
	
	public NeighbourFragment(){
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
	    MobclickAgent.onResume(getActivity());
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(getActivity());
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_neighbour, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		initView();
		initData();
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		super.onDestroy();
	}

	private void initView() { 
		initHeader("全部邻居", viewActionsContentView);
		headerTitle = (TextView) getView().findViewById(R.id.header_title);
		rightButton = (ImageButton) getView().findViewById(R.id.button_right);
		rightButton.setImageResource(R.drawable.setting_location_button);
		listView = (RTPullListView) getView().findViewById(R.id.listView1);
		rightButton.setVisibility(View.GONE);
		headerTitle.setOnClickListener(this);
	//	footView = (ViewGroup) getActivity().getLayoutInflater().inflate(
	//			R.layout.item_footer, null);
	//	listView.addFooterView(footView);
		
	}

	private void initData() {
		
		adapter = new NeighborListAdapter(getActivity(), list);
		listView.setAdapter(adapter);
		listView.setOnScrollStopAndEndListener(new OnScrollStopAndEndListener() {
			@Override
			public void onEndAndStopScroll() {
				if (!isLoading) {
				getList();
				}
			}
		});
		listView.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
	//			System.out.println("reRefresh");
				page = 1;
				isRefresh = true;
				getList();
			}
		});
		listView.goLoading();
	}

	public void getList() {
//		if (group.equals("0")) {
//			if (list.size() == 0) {
//				task = new RecommendListTask().execute();
//			}
//		} else {
			task = new ListTask().execute();
//		}
	}

	class ListTask extends AsyncTask<Void, Void, String> {
		private List<Space> aList;

		@Override
		protected void onPreExecute() {
			isLoading = true;
			if(!isRefresh){
		//		listView.addFooterView(footView);
			}
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				aList = SpaceService.friend(group, page + "", "");
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			if (result == null) {
				if(isRefresh){
					isRefresh = false;
					list.clear();
					listView.onRefreshComplete();
				}
		//		listView.removeFooterView(footView);
				
				if (aList != null) {
					list.addAll(aList);
					adapter.notifyDataSetChanged();
				}
			} else {
				getBaseActivity().showMessage(result);
			}
			isLoading = false;
			page++;
			super.onPostExecute(result);
		}
	}

	class RecommendListTask extends AsyncTask<Void, Void, String> {
		private List<Space> aList;

		@Override
		protected void onPreExecute() {
			isLoading = true;
	//		listView.addFooterView(footView);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				aList = SpaceService.recommendFriend();
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
	//		listView.removeFooterView(footView);
			if (result == null) {
				if (aList != null) {
					listView.onRefreshComplete();
					list.addAll(aList);
					adapter.notifyDataSetChanged();
				}
			} else {
				getBaseActivity().showMessage(result);
			}
			isLoading = false;
			super.onPostExecute(result);
		}
	}

	private void selectNeighbour() {
		groupList.clear();
		groupList.addAll(DataService.getGroupList());
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("选择分组");
		SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),
				groupList, android.R.layout.simple_list_item_1,
				new String[] { "gname" }, new int[] { android.R.id.text1 });
		builder.setAdapter(simpleAdapter,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (!isLoading) {
							group = (String) groupList.get(which).get("gid");
							headerTitle.setText((String) groupList.get(which)
									.get("gname"));
							page = 1;
							list.clear();
							getList();
						}
						dialog.dismiss();
					}
				});
		builder.show();
	}

	@Override
	public void onClick(View v) {
		if (headerTitle == v) {
			selectNeighbour();
		}
	}
}
